/*
 * @Author: Wanko
 * @Date: 2023-09-15 15:44:37
 * @LastEditors: Wanko
 * @LastEditTime: 2024-03-01 15:55:44
 * @Description:
 */
const Router = require('@koa/router')
const router = new Router()
const { baseUrl } = require('../config')
const debug = require('../env')
const path = require('path')

const Image = require('../models/Image')

router.post('/upload', async (ctx) => {
  const file = ctx.request.files.file
  const files = Array.isArray(file) ? file : [file]
  const data = files.map((item) => {
    const {
      originalFilename,
      filepath,
      size,
      mimetype,
      lastModifiedDate: created_time
    } = item

    const basename = path.basename(filepath)
    const { name, base, ext } = path.parse(filepath)
    const type = ext.replace('.', '')
    const url = debug ? `${ctx.origin}/${basename}` : `${baseUrl}/${basename}`

    return {
      size,
      base,
      name: originalFilename,
      type,
      url,
      path: filepath,
      created_time
    }
  })
  console.log(data);

  // const images = await Image.insertMany(data)
  const images = await Promise.all(
    data.map(async (imageData) => {
      const image = new Image(imageData)
      await image.save()
      return image
    })
  )
  // console.log(images)
  ctx.body = {
    code: 0,
    data: images,
    message: '上传成功'
  }
})

router.get('/', async (ctx) => {
  const images = await Image.find().select('-__v -_id')
  ctx.body = {
    code: 0,
    data: images,
    message: 'success'
  }
})
// 删除所有图片
router.delete('/', async (ctx) => {
  const images = await Image.deleteMany({})
  console.log(images)
  ctx.body = {
    code: 0,
    data: images,
    message: 'success'
  }
})

module.exports = router
